<template>
  <div class="position-container">
    <el-card class="position-header">
      <template #header>
        <div class="card-header">
          <h3>岗位职称管理</h3>
          <el-button type="success" @click="handleAdd">+ 新增岗位</el-button>
        </div>
      </template>

      <el-form :model="queryForm" :inline="true" label-width="80px">
        <el-form-item label="岗位名称">
          <el-input
            v-model="queryForm.title"
            placeholder="请输入岗位名称"
            clearable
            @keyup.enter="handleSearch"
            class="search-input"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="position-content">
      <el-table :data="positionList" border v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="岗位名称" min-width="200" />
        <el-table-column prop="group_names" label="角色组" min-width="150" />
        <el-table-column prop="user_count" label="人数" width="100" align="center" />
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.id === 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.page"
          v-model:page-size="queryForm.limit"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 岗位新增/编辑抽屉 -->
    <GlobalDrawer
      v-model="detailDrawerVisible"
      :title="dialogTitle"
      size="80%"
      @confirm="handleSave"
      @close="handleDetailDrawerClose"
    >
      <el-form
        v-if="!isViewMode"
        :model="detailForm"
        :rules="detailRules"
        ref="detailFormRef"
        label-width="100px"
      >
        <el-form-item label="岗位名称" prop="title">
          <el-input v-model="detailForm.title" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="角色组" prop="group_id">
          <el-checkbox-group v-model="detailForm.group_id">
            <el-checkbox v-for="group in groupList" :key="group.id" :label="group.id">
              {{ group.title }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="detailForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="detailForm.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <!-- 查看模式只读显示 -->
      <div v-else>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="岗位名称">{{ currentPosition.title }}</el-descriptions-item>
          <el-descriptions-item label="角色组">
            {{ currentPosition.group_names }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="currentPosition.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ currentPosition.remark || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider>权限详情</el-divider>

        <div class="permission-tree">
          <el-tree
            :data="permissionTree"
            show-checkbox
            node-key="id"
            :default-checked-keys="defaultCheckedKeys"
            :default-expanded-keys="defaultExpandedKeys"
            :props="{ label: 'title', children: 'children' }"
            disabled
          />
        </div>
      </div>
    </GlobalDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useUserStore } from '@/store'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { GlobalDrawer } from '@/components/common'
  import type { Position as PositionType } from '@/types/user'
  import { group } from '@/api/user/group'
  import { rule } from '@/api/home/rule'
  import { role } from '@/api/home/role'

  interface Group {
    id: number
    title: string
  }

  interface Permission {
    id: number
    title: string
    disabled?: boolean
    children?: Permission[]
  }

  // 扩展Position类型以支持列表页面额外字段
  interface ExtendedPosition extends PositionType {
    group_names?: string
    user_count?: number
  }

  const userStore = useUserStore()

  // 查询表单
  const queryForm = reactive({
    page: 1,
    limit: 15,
    title: '',
  })

  // 详情表单
  const detailForm = reactive({
    id: 0,
    title: '',
    group_id: [] as number[],
    status: 1,
    remark: '',
  })

  // 表单验证规则
  const detailRules = {
    title: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
    group_id: [{ required: true, message: '请选择角色组', trigger: 'change' }],
  }

  // 数据相关
  const positionList = ref<ExtendedPosition[]>([])
  const groupList = ref<Group[]>([])
  const total = ref(0)
  const loading = ref(false)

  // 抽屉相关
  const detailDrawerVisible = ref(false)
  const dialogTitle = ref('新增岗位')
  const isViewMode = ref(false)

  // 当前查看的岗位
  const currentPosition = ref<ExtendedPosition>({
    id: 0,
    title: '',
    group_names: '',
    user_count: 0,
    status: 1,
    remark: '',
    group_id: [],
    create_time: 0,
    update_time: 0,
  })

  // 权限树相关
  const permissionTree = ref<Permission[]>([])
  const defaultCheckedKeys = ref<number[]>([])
  const defaultExpandedKeys = ref<number[]>([])

  // 表单引用
  const detailFormRef = ref<FormInstance>()

  // 搜索
  const handleSearch = () => {
    queryForm.page = 1
    loadPositionList()
  }

  // 重置
  const handleReset = () => {
    queryForm.title = ''
    queryForm.page = 1
    loadPositionList()
  }

  // 加载岗位列表
  const loadPositionList = async () => {
    loading.value = true
    try {
      const res: any = await userStore.getPositionListAction(queryForm)
      console.log('岗位列表API响应:', res)

      if (res.code === 0) {
        // 增强数据解析适应性，处理不同的响应格式
        let positionData = []

        if (Array.isArray(res.data)) {
          // 标准格式：data直接是数组
          positionData = res.data
        } else if (res.data && Array.isArray(res.data.data)) {
          // 嵌套格式：data.data是数组
          positionData = res.data.data
        } else if (typeof res.data === 'object' && res.data !== null) {
          // 尝试从对象中提取数组
          const possibleArrays = Object.values(res.data).filter(val => Array.isArray(val))
          if (possibleArrays.length > 0) {
            positionData = possibleArrays[0]
          } else {
            positionData = []
          }
        } else {
          // 其他情况，使用空数组
          positionData = []
        }

        positionList.value = positionData
        total.value = res.count || res.data?.count || res.data?.total || positionData.length || 0

        console.log('解析后的岗位数据:', positionList.value)
        console.log('总记录数:', total.value)
      } else {
        ElMessage.error(res.msg || '获取岗位列表失败')
        positionList.value = []
        total.value = 0
      }
    } catch (error) {
      console.error('获取岗位列表异常:', error)
      ElMessage.error('获取岗位列表失败')
      positionList.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 加载用户组数据
  const loadGroupList = async () => {
    try {
      // 调用真实的API获取启用的用户组列表
      const response: any = await group.getActiveGroupList()
      if (response.code === 0) {
        // 确保数据结构正确，转换为组件需要的格式
        groupList.value = (response.data || []).map((item: any) => ({
          id: item.id,
          title: item.title,
          desc: item.desc || '',
        }))
        console.log('成功加载角色组数据:', groupList.value)
      } else {
        console.error('加载角色组失败:', response.msg)
        // 如果API失败，使用空数组而不是硬编码数据
        groupList.value = []
        ElMessage.error('加载角色组数据失败')
      }
    } catch (error) {
      console.error('加载角色组异常:', error)
      // 异常情况下使用空数组
      groupList.value = []
      ElMessage.error('加载角色组数据异常')
    }
  }

  // 新增岗位
  const handleAdd = async () => {
    isViewMode.value = false
    dialogTitle.value = '新增岗位'
    Object.assign(detailForm, {
      id: 0,
      title: '',
      group_id: [],
      status: 1,
      remark: '',
    })
    // 确保角色组已加载
    await loadGroupList()
    detailDrawerVisible.value = true
  }

  // 查看岗位
  const handleView = async (row: any) => {
    isViewMode.value = true
    dialogTitle.value = '查看岗位'
    currentPosition.value = { ...row }

    try {
      // 先加载角色组数据，确保数据已准备好
      await loadGroupList()

      // 获取真实的权限树数据 - 传递tree参数获取树形结构数据
      const ruleRes: any = await rule.getRuleList({ tree: true })
      if (ruleRes.code === 0 && ruleRes.data) {
        // 转换后端权限数据为组件需要的格式
        let allPermissions = formatRuleTree(ruleRes.data)
        allPermissions = allPermissions.filter(item => !item.disabled) // 过滤掉禁用的权限节点
        console.log('成功加载权限树数据:', allPermissions)

        // 根据岗位的角色组获取真实的权限数据
        if (row.group_id) {
          const groupIds = Array.isArray(row.group_id)
            ? row.group_id
            : String(row.group_id)
                .split(',')
                .map(id => parseInt(id.trim()))
                .filter(id => !isNaN(id))

          console.log('岗位角色组ID:', groupIds)

          // 获取选中角色组拥有的权限
          const permissionIds = await getGroupPermissions(groupIds)
          defaultCheckedKeys.value = permissionIds
          console.log('岗位拥有的权限ID:', permissionIds)

          // 过滤权限树，只保留拥有的权限及其父级节点
          if (permissionIds.length > 0) {
            permissionTree.value = filterPermissionTree(allPermissions, permissionIds)
          } else {
            // 如果没有权限ID，显示所有权限但不选中任何节点
            permissionTree.value = allPermissions
            console.log('没有权限ID，显示所有权限')
          }
        } else {
          defaultCheckedKeys.value = []
          // 如果没有角色组，显示所有权限但不选中任何节点
          permissionTree.value = allPermissions
          console.log('没有角色组，显示所有权限')
        }
      } else {
        console.error('获取权限树失败:', ruleRes.msg)
        // 如果API失败，使用空数组
        permissionTree.value = []
        ElMessage.error('获取权限数据失败')
      }

      // 设置默认展开的节点（展开所有有权限的父节点）
      const expandKeys = getExpandKeys(permissionTree.value, defaultCheckedKeys.value)
      defaultExpandedKeys.value = expandKeys

      console.log('=== 查看岗位调试信息 ===')
      console.log('岗位数据:', row)
      console.log('权限树:', permissionTree.value)
      console.log('选中的权限:', defaultCheckedKeys.value)
      console.log('展开的节点:', defaultExpandedKeys.value)
    } catch (error) {
      console.error('查看岗位时出错:', error)
      ElMessage.error('加载岗位详情失败')
      // 出错时使用空权限数据
      permissionTree.value = []
      defaultCheckedKeys.value = []
      defaultExpandedKeys.value = []
    }

    detailDrawerVisible.value = true
  }

  // 编辑岗位
  const handleEdit = async (row: any) => {
    isViewMode.value = false
    dialogTitle.value = '编辑岗位'

    try {
      // 先加载角色组数据，确保数据已准备好
      await loadGroupList()

      // 从API获取最新的岗位详情数据，确保group_id是最新的
      const detailRes: any = await userStore.getPositionDetail(row.id)
      let positionData = row

      if (detailRes.code === 0 && detailRes.data) {
        // 使用API返回的最新数据
        positionData = detailRes.data
        console.log('从API获取的岗位详情：', positionData)
      } else {
        console.warn('无法从API获取岗位详情，使用列表数据：', row)
      }

      // 处理group_id数据格式，转换为数组
      let groupIdArray: number[] = []
      const groupId = positionData.group_id

      // 类型检查和转换
      if (groupId !== null && groupId !== undefined) {
        if (Array.isArray(groupId)) {
          // 如果已经是数组，直接使用
          groupIdArray = groupId
        } else {
          // 将其他类型转为字符串处理
          const groupIdStr = String(groupId)
          if (groupIdStr.trim() !== '') {
            // 如果是字符串，转换为数组
            groupIdArray = groupIdStr
              .split(',')
              .map(id => parseInt(id.trim()))
              .filter(id => !isNaN(id))
          }
        }
      }

      // 重置detailForm确保重新渲染
      detailForm.id = positionData.id
      detailForm.title = positionData.title
      detailForm.group_id = groupIdArray
      detailForm.status = positionData.status || 1
      detailForm.remark = positionData.remark || ''

      detailDrawerVisible.value = true

      console.log('=== 编辑岗位调试信息 ===')
      console.log('原始岗位数据：', row)
      console.log('API返回的岗位数据：', positionData)
      console.log('转换后的group_id数组：', groupIdArray)
      console.log('角色组列表：', groupList.value)
      console.log('当前detailForm.group_id：', detailForm.group_id)
      console.log('原始group_id类型：', typeof positionData.group_id)
      console.log('原始group_id值：', positionData.group_id)

      // 延迟一点再打印，确保Vue完成更新
      setTimeout(() => {
        console.log('延迟后的detailForm.group_id：', detailForm.group_id)
        console.log('groupList值匹配检查：')
        groupList.value.forEach(group => {
          const isSelected = detailForm.group_id.includes(group.id)
          console.log(
            `  角色组 "${group.title}" (ID: ${group.id}): ${isSelected ? '已选中' : '未选中'}`
          )
        })
      }, 100)
    } catch (error) {
      console.error('编辑岗位时出错：', error)
      // 如果出错，仍然显示编辑抽屉，但使用原始数据
      detailForm.id = row.id
      detailForm.title = row.title
      detailForm.group_id = []
      detailForm.status = row.status || 1
      detailForm.remark = row.remark || ''
      detailDrawerVisible.value = true
    }
  }

  // 保存岗位
  const handleSave = () => {
    if (!detailFormRef.value) return

    detailFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        // 处理表单数据，将group_id数组转为逗号分隔的字符串
        const formData: any = Object.assign({}, detailForm)
        if (Array.isArray(formData.group_id)) {
          formData.group_id = formData.group_id.join(',')
        }

        try {
          const res: any = await userStore.savePositionAction(formData)
          if (res.code === 0) {
            ElMessage.success(res.msg || '保存成功')
            detailDrawerVisible.value = false
            loadPositionList()
          } else {
            ElMessage.error(res.msg || '保存失败')
          }
        } catch (error) {
          ElMessage.error('保存失败')
        }
      }
    })
  }

  // 抽屉关闭处理
  const handleDetailDrawerClose = () => {
    isViewMode.value = false
    if (detailFormRef.value) {
      detailFormRef.value.resetFields()
    }
    Object.assign(detailForm, {
      id: 0,
      title: '',
      group_id: [],
      status: 1,
      remark: '',
    })
  }

  // 删除岗位
  const handleDelete = (row: any) => {
    ElMessageBox.confirm('确定要删除该岗位吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res: any = await userStore.deletePositionAction(row.id)
          if (res.code === 0) {
            ElMessage.success(res.msg || '删除成功')
            loadPositionList()
          } else {
            ElMessage.error(res.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        // 取消操作
      })
  }

  // 分页相关
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    queryForm.page = 1
    loadPositionList()
  }

  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    loadPositionList()
  }

  // 格式化权限树数据，将后端数据转换为组件需要的格式
  const formatRuleTree = (data: any[]): Permission[] => {
    if (!Array.isArray(data)) return []

    return data
      .map(item => ({
        id: item.id,
        title: item.title || item.name || '未命名',
        children:
          item.children && Array.isArray(item.children) ? formatRuleTree(item.children) : [],
      }))
      .filter(item => item.id && item.title)
  }

  // 获取用户组拥有的权限ID列表
  const getGroupPermissions = async (groupIds: number[]): Promise<number[]> => {
    try {
      console.log('=== 开始获取用户组权限 ===')
      console.log('输入的用户组ID:', groupIds)

      const permissionIds: number[] = []

      for (const groupId of groupIds) {
        console.log(`\n--- 处理用户组ID: ${groupId} ---`)

        try {
          // 获取用户组详情以获取权限信息
          const groupDetail = await group.getGroupDetail(groupId)
          console.log(`获取用户组${groupId}详情响应:`, groupDetail)

          if (groupDetail && groupDetail.code === 0 && groupDetail.data) {
            console.log('用户组详情数据:', groupDetail.data)

            // 从用户组数据中提取权限ID
            const groupRules = groupDetail.data.rules_array || groupDetail.data.rules
            console.log(`用户组${groupId}的权限数据:`, groupRules)
            console.log(`权限数据类型:`, typeof groupRules)
            console.log(`权限数据是否为数组:`, Array.isArray(groupRules))

            if (groupRules) {
              let ids: number[] = []

              if (Array.isArray(groupRules)) {
                // 如果已经是数组
                ids = groupRules
                console.log(`用户组${groupId}使用数组形式的权限ID:`, ids)
              } else if (typeof groupRules === 'string') {
                // 如果是字符串，转换为数组
                ids = String(groupRules)
                  .split(',')
                  .map(id => parseInt(id.trim()))
                  .filter(id => !isNaN(id))
                console.log(`用户组${groupId}字符串转换后的权限ID:`, ids)
              } else {
                console.warn(`用户组${groupId}的权限数据格式异常:`, groupRules)
              }

              console.log(`用户组${groupId}最终权限ID:`, ids)
              permissionIds.push(...ids)
            } else {
              console.log(`用户组${groupId}没有权限数据`)
            }
          } else {
            console.error(`用户组${groupId}详情获取失败:`, groupDetail)

            // 检查是否有具体的错误信息
            if (groupDetail && groupDetail.msg) {
              console.error(`错误信息:`, groupDetail.msg)
            }
          }
        } catch (error) {
          console.error(`获取用户组${groupId}详情时发生异常:`, error)
        }
      }

      // 去重并返回
      const uniqueIds = [...new Set(permissionIds)]
      console.log('\n=== 权限获取完成 ===')
      console.log('所有权限ID（未去重）:', permissionIds)
      console.log('最终权限ID列表（去重后）:', uniqueIds)
      console.log('=== 权限获取结束 ===\n')

      return uniqueIds
    } catch (error) {
      console.error('获取用户组权限整体失败:', error)
      return []
    }
  }

  // 过滤权限树，只保留拥有的权限及其父级节点
  const filterPermissionTree = (treeData: Permission[], checkedKeys: number[]): Permission[] => {
    // 如果没有权限ID，直接返回所有权限
    if (!checkedKeys || checkedKeys.length === 0) {
      return treeData
    }

    const traverse = (nodes: Permission[]): Permission[] => {
      const result: Permission[] = []

      nodes.forEach(node => {
        // 检查当前节点是否在权限列表中
        const hasPermission = checkedKeys.includes(node.id)
        let filteredChildren: Permission[] = []

        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          filteredChildren = traverse(node.children)
        }

        // 如果当前节点有权限，或者有拥有权限的子节点，则保留该节点
        if (hasPermission || filteredChildren.length > 0) {
          // 保留原始节点的所有属性，确保不会丢失必要信息
          const newNode: Permission = {
            ...node,
            children: filteredChildren.length > 0 ? filteredChildren : undefined,
          }

          result.push(newNode)
        }
      })

      return result
    }

    const filtered = traverse(treeData)
    console.log('过滤后的权限树:', filtered)
    return filtered
  }

  // 获取需要展开的节点（基于已选中的权限）
  const getExpandKeys = (treeData: Permission[], checkedKeys: number[]): number[] => {
    const expandKeys: number[] = []

    const traverse = (nodes: Permission[], depth = 0) => {
      nodes.forEach(node => {
        // 如果当前节点或其子节点有选中项，则展开
        const hasCheckedChild = checkedKeys.some(
          key => key === node.id || (node.children && node.children.some(child => child.id === key))
        )

        if (hasCheckedChild) {
          expandKeys.push(node.id)
        }

        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          traverse(node.children, depth + 1)
        }
      })
    }

    traverse(treeData)
    return expandKeys
  }

  // 初始化加载
  onMounted(() => {
    loadPositionList()
    loadGroupList()
  })
</script>

<style scoped>
  .position-container {
    padding: 20px;
  }

  .position-header {
    margin-bottom: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .card-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .position-content {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }

  .permission-tree {
    margin-top: 20px;
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    padding: 10px;
    border-radius: 4px;
  }

  /* 搜索表单样式 */
  .position-header :deep(.el-form--inline) {
    margin-top: 20px;
  }

  .search-input {
    width: 200px;
  }

  /* 抽屉内容样式 */
  .GlobalDrawer :deep(.drawer-body) {
    padding: 20px;
  }

  .GlobalDrawer :deep(.el-form) {
    max-width: 600px;
  }

  .GlobalDrawer :deep(.el-form-item) {
    margin-bottom: 20px;
  }

  .GlobalDrawer :deep(.el-checkbox-group) {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .GlobalDrawer :deep(.el-checkbox) {
    margin-right: 20px;
  }

  .permission-tree {
    margin-top: 20px;
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    padding: 10px;
    border-radius: 4px;
  }

  .permission-tree :deep(.el-tree-node__content) {
    height: 30px;
  }

  .permission-tree :deep(.el-tree-node__label) {
    font-size: 13px;
  }
</style>
